require 'icalendar'

class CalendarController < ApplicationController
  before_filter :login_required
  
  
  def index
  end
  
  def select_project
    p_id = params[:id]
    u = User.find(session['user'])
    taskcond  = "done=0 and user_id='#{u.id}' and duedate<=CURRENT_DATE()+ INTERVAL 2 month"
    if(p_id == nil || p_id == "undefined")
      calcond  = "user_id=#{u.id}"
      pids = u.active_projects_ids.join(',')
      taskcond += " and project_id in (#{pids})" if(pids != '')
      msg = 'Displaying all <b>your</b> events'
    else
      calcond = "project_id=#{p_id}"
      taskcond += " and " + calcond
      msg = 'Displaying <b>project</b> events'
    end
    e = Calendar.find(:all, :conditions=>calcond)
    t = Task.find(:all, :conditions=>taskcond)
    @events =(e.map{  |e| {:type=>'cal', :id=>e.id, :title=>e.title,:date=>e.date, :project=>e.project.name}} + t.map{|e| {:type=>'task',:id=>e.id, :title=>e.title,:date=>e.duedate, :project=>e.project.name}}).sort_by {|e| e[:date]?e[:date]:Date.today}
    render(:partial=>'events', :locals=>{:msg=>msg})
  end
  
  def create
    p_id = params[:new][:project_id]
    render(:text=>'You have to select a project') and return if(p_id=='')
    c = Calendar.new(params[:new])
    c.user_id = session['user']
    c.save
    redirect_to(:action=>'select_project', :id=>p_id)
  end
  
  # Ajaxed
  def delete
    id = params[:id]
    begin
      t = Calendar.find(id)
    rescue Exception => e
      render(:text=>'-1') and return
    end
    # or (t.project_id) TODO: add something to verify if the event is on a project we are member of
    # t.user_id != 0 # commented so we can delete old events that had no user_id at the time of creation (old version of PTM)
    if Calendar.destroy(id)
      render(:text=>"#{id}")
    else
      render(:text=>'-2')
    end
  end
  
  # Work In Progress
  def export_events
    @events = Calendar.find(:all)
    @calendar = Icalendar::Calendar.new
    event = Icalendar::Event.new
    event.start = @event.dt_time.strftime("%Y%m%dT%H%M%S")
    event.end = @event.dt_time.strftime("%Y%m%dT%H%M%S")
    event.summary = @event.summary
    event.description = @event.description
    event.location = @event.location
    @calendar.add event
    @calendar.publish
    headers['Content-Type'] = "text/calendar; charset=UTF-8"
    render_without_layout :text => @calendar.to_ical
  end
  
end
